<template>
  <div class="memory-container">
    <div class="text-gradient">
      <h2>设备内存占比</h2>
    </div>

    <div class="body-box" v-if="ranking.data.length > 0">
      <dv-scroll-ranking-board class="dv-scr-rank-board" :config="ranking" />
    </div>
  </div>
</template>

<script>
import { cpuAndMem } from '@/api/homePage'

export default {
  data() {
    return {
      ranking: {
        data: [],
        carousel: 'single',
        unit: ' %'
      },
      currentIndex: 0,
      interval: null
    }
  },

  mounted() {
    this.doQuery()
    this.startCarousel()
  },

  beforeDestroy() {
    clearInterval(this.interval) // 清除定时器
  },

  methods: {
    async doQuery() {
      try {
        const {
          data: { data }
        } = await cpuAndMem()

        this.ranking.data = data.memList.map(item => ({
          name: item.name,
          value: item.usedMem
        }))

        if (this.ranking.data.length < 5) {
          const additionalData = []
          this.ranking.data = this.ranking.data.concat(
            additionalData.slice(0, 5 - this.ranking.data.length)
          )
        }
      } catch (error) {
        console.error('获取 CPU 和内存数据失败:', error)
      }
    },

    startCarousel() {
      this.interval = setInterval(() => {
        this.nextItem()
      }, 3000) // 每3秒切换一次
    },

    nextItem() {
      this.currentIndex = (this.currentIndex + 1) % this.ranking.data.length
      this.updateRankingDisplay()
    },

    previousItem() {
      this.currentIndex =
        (this.currentIndex - 1 + this.ranking.data.length) %
        this.ranking.data.length
      this.updateRankingDisplay()
    },

    updateRankingDisplay() {
      this.ranking.data = [this.ranking.data[this.currentIndex]]
    }
  }
}
</script>

<style lang="scss" scoped>
.memory-container {
  height: 100%;
  width: 100%;
  padding: 10px;

  .body-box {
    .dv-scroll-ranking-board {
      width: 100%;
      height: 300px;
    }
  }
}

.text-gradient {
  color: #fff;
  display: flex;
  line-height: 50px;
  align-items: center;
  justify-content: center;
}

.dv-scroll-ranking-board .row-item .ranking-info {
  font-size: 18px !important;
}

.dv-scroll-ranking-board .row-item .ranking-info .rank {
  display: none !important;
}
</style>
